package org.grayrabbit.cloud.core.telnet;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class TelnetService implements Runnable {
	protected int bindPort = 23;
	protected Thread thread;
	protected ServerSocket serverSocket;
	private TelnetSessionControllerFactory controllerFactory;
	private TelnetPrintConfiguration printConfiguration;

	public boolean setPrintConfiguration(
			TelnetPrintConfiguration printConfiguration) {
		if (this.thread == null) {
			this.printConfiguration = printConfiguration;
			return true;
		}

		return false;
	}

	public boolean setTelnetSessionControllerFactory(
			TelnetSessionControllerFactory controllerFactory) {
		if (this.thread == null) {
			this.controllerFactory = controllerFactory;
			return true;
		}

		return false;
	}

	public int getBindPort() {
		return this.bindPort;
	}

	public boolean setBindPort(int bindPort) {
		if (this.thread == null) {
			this.bindPort = bindPort;
			return true;
		}

		return false;
	}

	public void start() throws IOException {
		this.thread = new Thread(this);
		this.thread.setName("Telnet Service");
		this.thread.setDaemon(true);

		this.serverSocket = new ServerSocket(getBindPort());

		this.thread.start();
	}

	public void stop() throws IOException {
		this.serverSocket.close();

		this.serverSocket = null;
		this.thread.interrupt();
		this.thread = null;
	}

	public void run() {
		while (this.thread != null) {
			Socket socket = null;
			try {
				socket = this.serverSocket.accept();
			} catch (SocketTimeoutException localSocketTimeoutException) {
			} catch (IOException e) {
				if (this.serverSocket == null)
					break;
			}
			if (this.serverSocket.isClosed()) {
				break;
			}

			if (socket == null)
				continue;
			try {
				TelnetSession session = new TelnetSession(
						this.printConfiguration,
						this.controllerFactory.createSessionController(),
						socket);

				session.start();
			} catch (TelnetServiceException e) {
				e.printStackTrace();
			}
		}
	}
}
